package linc.fun.openai.service.impl;


import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import linc.fun.openai.domain.entity.chat.ChatUserBindingEmailDO;
import linc.fun.openai.mapper.ChatUserBindingEmailMapper;
import linc.fun.openai.service.ChatUserBindingEmailService;
import linc.fun.openai.util.ThrowExceptionUtil;
import org.springframework.stereotype.Service;

import java.util.Objects;

import static linc.fun.openai.domain.entity.chat.table.Tables.ChatUserBindingEmail;

/**
 * 前端用户邮箱扩展业务实现类
 *
 * @author linc
 */
@Service
public class ChatUserBindingEmailServiceImpl extends ServiceImpl<ChatUserBindingEmailMapper, ChatUserBindingEmailDO> implements ChatUserBindingEmailService {

    @Override
    public boolean isUsed(String username) {
        ChatUserBindingEmailDO userExtraEmail = this.getOne(QueryWrapper.create().
                select(ChatUserBindingEmail.Verified, ChatUserBindingEmail.Id)
                .where(ChatUserBindingEmail.Username.eq(username)));
        if (Objects.isNull(userExtraEmail)) {
            return false;
        }
        return userExtraEmail.getVerified();
    }

    @Override
    public ChatUserBindingEmailDO getUnverifiedEmailAccount(String identity) {
        return this.getOne(QueryWrapper.create()
                .where(ChatUserBindingEmail.Username.eq(identity))
                .and(ChatUserBindingEmail.Verified.eq(false)));
    }

    @Override
    public ChatUserBindingEmailDO getEmailAccount(String username) {
        return this.getOne(QueryWrapper.create()
                .where(ChatUserBindingEmail.Username.eq(username)));
    }

    @Override
    public void verifySuccess(ChatUserBindingEmailDO userBindingEmail) {
        userBindingEmail.setVerified(true);
        ThrowExceptionUtil.isFalse(this.update(userBindingEmail, QueryWrapper.create()
                        .where(ChatUserBindingEmail.Verified.eq(false))
                        .and(ChatUserBindingEmail.Username.eq(userBindingEmail.getUsername())))
                )
                .throwMessage("邮箱验证码失败");
    }
}
